#!/bin/sh

# TCE - Tight Control Environment: Hosting Platform   
# Copyright (c) 2006 by the TightControl Dev Team
# http://tce.mystichost.net
#
#
# License:
#    This program is free software; you can redistribute it and/or
#    modify it under the terms of the MPL Mozilla Public License
#    as published by the Free Software Foundation; either version 1.1    
#    of the License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
#    MPL Mozilla Public License for more details.
#    
#    You may have received a copy of the MPL Mozilla Public License
#    along with this program.
#    
#    An on-line copy of the MPL Mozilla Public License can be found
#    http://www.mozilla.org/MPL/MPL-1.1.html
#
#
# The TCE Home Page is at:
#
#    http://tce.mystichost.net

# Settings
TCE_INSTALLER_VERSION="0.2.1"
# PHP 5 Location
TCE_PHP5_SUB="be2"
TCE_PHP5_FILE="php-5.1.6.tar.gz"
TCE_PHP5_FOLDER="php-5.1.6"
TCE_PHP5_MD5="04d6166552289eaeff771f5ec953b065"
TCE_PHP5_URL="http://$TCE_PHP5_SUB.php.net/get/$TCE_PHP5_FILE/from/this/mirror"
TCE_PHP5_PATH="/usr/local/php"

# Apache 2 Location
TCE_APACHE2_MIRROR="http://apache.scarlet.be/httpd"
TCE_APACHE2_FILE="httpd-2.0.59.tar.gz"
TCE_APACHE2_URL="$TCE_APACHE2_MIRROR/$TCE_APACHE2_FILE"
# What folder will get created when unpacking the package?
TCE_APACHE2_FOLDER="httpd-2.0.59"
TCE_APACHE2_MD5="35a4cebaa6b4548f9a48375ea9629c8f"

TCE_APACHE2_CONF_TEMPLATE="http://tce.mystichost.net/setup/files/httpd.conf"
# The root folder and the tmp install folder
TCE_DEFAULT_ROOT="/usr/local/tce"
# WARNING - NEVER put this as / !!
TCE_TEMP="/tmp/tce" 
TCE_TARGET_OS="Ubuntu Dapper"

# TODO : Set from argument?
TCE_ROOT="$TCE_DEFAULT_ROOT"
TCE_SYS="$TCE_ROOT/sys"
TCE_WEBROOT="$TCE_ROOT/web"

######### PLEASE DO NOT ALTER BELOW #########
TCE_PHP5_PREFIX="$TCE_SYS/php5"
TCE_APACHE2_PREFIX="$TCE_SYS/apache2"
TCE_GROUP="tcontrol"
TCE_USER="tcontrol"
TCE_HOSTNAME=`hostname`
TCE_PORT=3131
TCE_SSL_PORT=3132

TCE_KEY="temp" # TODO this should be randomly generated and is used for the first time configuration
apache2Dependencies() {
	adduser "$TCE_USER" --quiet --disabled-login --no-create-home > /dev/null 2>&1
	addgroup "$TCE_GROUP" --quiet  > /dev/null 2>&1


	if apt-get install libssl-dev -qq; then
		return 0
	else

		return 1
	fi  
}


# Global Dependencies
globalDependencies(){
    if apt-get install libmysqlclient15-dev libncurses5-dev unzip autoconf automake1.4 autotools-dev binutils bison cpp cpp-4.0 cpp-4.0-doc cpp-doc flex gcc gcc-4.0 gcc-4.0-doc gcc-4.0-locales gcc-doc gdb lib64gcc1 libc6-amd64 libc6-dev libc6-dev-amd64 libssl-dev libtool linux-kernel-headers m4 make manpages-dev zlib1g-dev autoconf automake1.9 autotools-dev binutils binutils-doc bison cpp cpp-4.0 cpp-4.0-doc cpp-doc flex gcc gcc-4.0 gcc-4.0-doc gcc-4.0-locales gcc-doc gdb m4 autoconf automake1.9 autotools-dev binutils binutils-doc bison cpp cpp-4.0 cpp-4.0-doc cpp-doc flex gcc gcc-4.0 gcc-4.0-doc gcc-4.0-locales gcc-doc gdb lib64gcc1 libc6-amd64 libc6-dev libc6-dev-amd64 libssl-dev libtool linux-kernel-headers m4 make manpages-dev zlib1g-dev ; then
        return 0
    else
        return 1
    fi
}

# PHP 5 Dependencies
php5Dependencies() {
    if apt-get install libxml2-dev libbz2-dev comerr-dev curl libcurl3 libcurl3-dev libcurl3-openssl-dev libidn11 libidn11-dev libkadm55 libkrb5-dev pkg-config libqdbm++-dev libqdbm-dev libqdbm11 libqdbm2++c2 libgdbm-dev libjpeg-mmx-dev libjpeg62 libjpeg62-dev libpng12-0 libpng12-dev defoma fontconfig laptop-detect libexpat1 libexpat1-dev libfontconfig1 libfontconfig1-dev libfreetype6 libfreetype6-dev libgd2-xpm libgd2-xpm-dev libx11-6 libx11-dev libxau-dev libxau6 libxdmcp-dev libxdmcp6 libxpm-dev libxpm4 ttf-bitstream-vera ttf-dejavu ttf-freefont x11-common x11proto-core-dev x11proto-input-dev x11proto-kb-dev libice-dev libice6 libsm-dev libsm6 libt1-5 libt1-dev libxext-dev libxext6 libxi-dev libxi6 x11proto-xext-dev libc-client-dev libc-client2002edebian libpam0g-dev mlock libltdl3 libltdl3-dev libmcrypt-dev libmcrypt4 libmhash-dev libmhash2 libming-dev libming0 libungif4g libmysqlclient15-dev libncurses5-dev libpq-dev postgresql-server-dev-8.1 libaspell-dev libaspell15 libpspell-dev -qq; then
        return 0
    else

        return 1
    fi  
}

# Create root folder
prepareTemp() {
     if [ -d $TCE_TEMP ]
     then
        echo "Temp folder $TCE_TEMP already exists. Skipping..."
        return 0
     else
     		Res=`mkdir $TCE_TEMP`;
     		return $Res;
     fi
}

### PHP 5 STUFF ###
# Try to fetch the PHP5 sourcecode
fetchPHP5() {
if wget "$TCE_PHP5_URL" --output-document "$TCE_PHP5_FILE"; then
	return 0
else
	return 1
fi
}
verifyPHP5(){
	MD5Check=`md5sum $TCE_PHP5_FILE | cut -d " " -f 1`; 
	if [ "$MD5Check" = "$TCE_PHP5_MD5" ]
	then
		return 0
	fi

	return 1
}


unpackPHP5() {
	if gunzip -c "$TCE_PHP5_FILE" | tar -xvf -; then
		return 0
	else
		return 1
	fi
}


moveIntoPHP5() {
	if cd $TCE_PHP5_FOLDER; then
		return 0
	else
		return 1
	fi
}


# Configure PHP
configurePHP5() {
	if ./configure --prefix="$TCE_PHP5_PREFIX" --with-apxs2="$TCE_APACHE2_PREFIX/bin/apxs" --enable-cli --disable-cgi --disable-soap --enable-memory-limit --with-pear="$TCE_SYS/pear" --enable-sigchild --with-openssl --with-kerberos --with-pcre-regex --with-zlib --enable-bcmath --with-bz2 --enable-calendar --with-curl --with-curlwrappers --enable-dba  --with-inifile --with-flatfile --with-gdbm  --enable-dbase --with-libxml-dir --enable-exif --enable-filepro --enable-ftp   --with-openssl-dir --with-gd --with-jpeg-dir --with-png-dir --with-zlib-dir --with-xpm-dir --with-ttf --with-freetype-dir --with-t1lib --enable-gd-native-ttf --enable-gd-jis-conv --with-gettext --with-imap --with-kerberos --with-imap-ssl --enable-mbstring --with-mcrypt --with-mhash --with-ming --with-mysql --with-zlib-dir --with-mysqli --with-ncurses  --with-pdo-mysql --with-pdo-pgsql --with-pdo-sqlite --with-pgsql --with-libxml-dir --with-openssl-dir --with-pspell --enable-soap --enable-sockets --enable-sqlite-utf8; then
		return 0
	else
		return 1
	fi
}
cleanPHP5() {
	if make clean; then
		return 0
	else
		return 1
	fi
}

compilePHP5() {
	if make; then
		return 0
	else
		return 1
	fi
}


installPHP5() {
	if make install; then
		return 0
	else
		return 1
	fi
}


### APACHE 2 STUFF ###
# Try to fetch the PHP5 sourcecode
fetchApache2() {
if wget "$TCE_APACHE2_URL" --output-document "$TCE_APACHE2_FILE"; then
	return 0
else
	return 1
fi
}
verifyApache2(){
	MD5Check=`md5sum $TCE_APACHE2_FILE | cut -d " " -f 1`; 
	if [ "$MD5Check" = "$TCE_APACHE2_MD5" ]
	then
		return 0
	fi

	return 1
}


unpackApache2() {
	if gunzip -c "$TCE_APACHE2_FILE" | tar -xvf -; then
		return 0
	else
		return 1
	fi
}


moveIntoApache2() {
	if cd $TCE_APACHE2_FOLDER; then
		return 0
	else
		return 1
	fi
}


# Configure PHP with ncurses and sqlite utf8 support
configureApache2() {
	if ./configure --prefix="$TCE_APACHE2_PREFIX" --enable-module=most --enable-shared=max --enable-ssl --enable-so --enable-rewrite --enable-vhost-alias --enable-cgi --enable-cgid --enable-http --enable-file-cache --config-cache --with-server-uid="$TCE_USER" --with--server-gid="$TCE_GROUP" --with-z --enable-rewrite; then
		return 0
	else
		return 1
	fi
}
cleanApache2() {
	if make clean; then
		return 0
	else
		return 1
	fi
}

compileApache2() {
	if make; then
		return 0
	else
		return 1
	fi
}


installApache2() {
	if make install; then
		return 0
	else
		return 1
	fi
}

# Generate a new key
mod_sslGenerate(){
    mkdir "$TCE_APACHE2_PREFIX/conf/ssl.crt/" > /dev/null 2>&1
    mkdir "$TCE_APACHE2_PREFIX/conf/ssl.key/" > /dev/null 2>&1
    if openssl req -new -x509 -nodes -out "$TCE_APACHE2_PREFIX/conf/ssl.crt/server.crt" -keyout "$TCE_APACHE2_PREFIX/conf/ssl.key/server.key"; then
        return 0
    fi
    
    return 1
}

echo "Starting TCE Installer V$TCE_INSTALLER_VERSION!";
echo
echo "This will install the latest Tight Control Environment"
echo "This installer is tweaked for $TCE_TARGET_OS and may fail or be incomplete for other/older operating systems"
echo
echo "After the installation, you will be able to configure it with your webbrowser"
echo "-- Press enter to continue or ctrl-c to stop the installer! --"
read -e IGNORED_ENTRY


# Prepare the temp folder
echo "Preparing temporary folder $TCE_TEMP"
if prepareTemp;
then
	echo "Done!"
else
	echo "Error: Could not prepare the temporary directory for installation. Canceling..."
	exit 1
fi

# Move into it
echo "Moving to $TCE_TEMP..."
if cd $TCE_TEMP;
then
	echo "Done!"
else
	echo "Error: Could not move into the temporary directory for installation. Canceling..."
	exit 1
fi

# Install global dependencies
echo "Installing global dependencies..."
if globalDependencies;
then
	echo "Done!"
else
	echo "Error: Could not install global dependencies. Canceling..."
	exit 1
fi


### APACHE2 STUFF
echo "Installing Apache2 dependencies and creating tcontrol user/group..."
if apache2Dependencies;
then
	echo "Done!"
else
	echo "Error: Could not install the Apache2 dependencies. Canceling..."
	exit 1
fi

echo "Fetching Apache2..."
if fetchApache2;
then
	echo "Done!"
else
	echo "Error: Could not fetch the Apache2 sources. Canceling..."
	exit 1
fi

# Verify the package
echo "Verifying the Apache2 package..."
if verifyApache2;
then
	echo "Done!"
else
	echo "Error: Could not verify the Apache2 package. Canceling..."
	exit 1
fi

# Unpack the package
echo "Unpacking the Apache2 package..."
if unpackApache2;
then
	echo "Done!"
else
	echo "Error: Could not unpack the Apache2 package. Canceling..."
	exit 1
fi

# Move to the unpacked folder
echo "Moving into the extracted Apache2 folder..."
if moveIntoApache2;
then
	echo "Done!"
else
	echo "Error: Could not move into the extracted Apache2 folder. Canceling..."
	exit 1
fi



# Start the configuration process
# echo "-- Press enter to start the Apache2 configuration --"
# read -e IGNORED_ENTRY

# Configure Apache2
echo "Configuring Apache2..."
if configureApache2;
then
	echo "Done!"
else
	echo "Error: Could not configure Apache2. Please, check for missing libraries and try to install them yourself. Then, rerun the installer. Canceling..."
	exit 1
fi

# Make Apache2
echo "Compiling Apache2..."
if compileApache2;
then
	echo "Done!"
else
	echo "Error: Could not compile Apache2. Canceling..."
	exit 1
fi

# Install Apache2
echo "Installing Apache2..."
if installApache2;
then
	echo "Done!"
else
	echo "Error: Could not install Apache2. Canceling..."
	exit 1
fi

# Make Apache2
# echo "Cleaning Apache2..."
# if cleanApache2;
# then
# 	echo "Done!"
# else
# 	echo "Error: Could not clean Apache2. Canceling..."
# 	exit 1
# fi

echo "Generating Self Signed Certificate..."
if mod_sslGenerate;
then
	echo "Done!"
else
	echo "Error: Could not generate a self signed certificate. Canceling..."
	ext 1
fi

### PHP5 STUFF
echo "Installing PHP5 dependencies..."
if php5Dependencies;
then
	echo "Done!";
else
	echo "Error: Could not install all required dependencies. Canceling..."
	exit 1
fi

# Move into it
echo "Fetching PHP5..."
if fetchPHP5;
then
	echo "Done!"
else
	echo "Error: Could not fetch the PHP5 sources. Canceling..."
	exit 1
fi

# Verify the package
echo "Verifying the PHP5 package..."
if verifyPHP5;
then
	echo "Done!"
else
	echo "Error: Could not verify the PHP5 package. Canceling..."
	exit 1
fi

# Unpack the package
echo "Unpacking the PHP5 package..."
if unpackPHP5;
then
	echo "Done!"
else
	echo "Error: Could not unpack the PHP5 package. Canceling..."
	exit 1
fi

# Move to the unpacked folder
echo "Moving into the extracted PHP5 folder..."
if moveIntoPHP5;
then
	echo "Done!"
else
	echo "Error: Could not move into the extracted PHP5 folder. Canceling..."
	exit 1
fi



# Start the configuration process
# echo "-- Press enter to start the PHP5 configuration --"
# read -e IGNORED_ENTRY

# Configure PHP5
echo "Configuring PHP5..."
if configurePHP5;
then
	echo "Done!"
else
	echo "Error: Could not configure PHP5. Please, check for missing libraries and try to install them yourself. Then, rerun the installer. Canceling..."
	exit 1
fi

# Make PHP5
echo "Compiling PHP5..."
if compilePHP5;
then
	echo "Done!"
else
	echo "Error: Could not compile PHP5. Canceling..."
	exit 1
fi

# Install PHP5
echo "Installing PHP5..."
if installPHP5;
then
	echo "Done!"
else
	echo "Error: Could not install PHP5. Canceling..."
	exit 1
fi

# Clean PHP5
# echo "Cleaning PHP5..."
# if cleanPHP5;
# then
# 	echo "Done!"
# else
# 	echo "Error: Could not clean PHP5. Canceling..."
# 	exit 1
# fi

# Create the webfolder
echo "Creating the webroot..."
mkdir "$TCE_WEBROOT"; 
echo "Done!"
# if mkdir "$TCE_WEBROOT"; 
# then
# 	echo "Done!"
# else
# 	echo "Error: Could not create the webroot. Canceling..."
# 	exit 1
# fi

# Fetch the apache2 config :)
echo "Fetching the Apache2 configuration template..."
if wget  "$TCE_APACHE2_CONF_TEMPLATE" --output-document "$TCE_APACHE2_PREFIX/conf/httpd.conf.template"; 
then
	echo "Done!"
else
	echo "Error: Could not fetch the Apache2 configuration template. Canceling..."
	exit 1
fi

# Parse the template :)
echo "Parsing the template..."
# I know : ugly atm, but it should work ;)
sed "s:#TCE_WEBROOT#:$TCE_WEBROOT:g" $TCE_APACHE2_PREFIX/conf/httpd.conf.template > $TCE_APACHE2_PREFIX/conf/httpd.conf.tmp
cp "$TCE_APACHE2_PREFIX/conf/httpd.conf.tmp" "$TCE_APACHE2_PREFIX/conf/httpd.conf.template" -f
sed "s:#TCE_PORT#:$TCE_PORT:g" $TCE_APACHE2_PREFIX/conf/httpd.conf.template > $TCE_APACHE2_PREFIX/conf/httpd.conf.tmp
cp "$TCE_APACHE2_PREFIX/conf/httpd.conf.tmp" "$TCE_APACHE2_PREFIX/conf/httpd.conf.template" -f
sed "s:#TCE_SSL_PORT#:$TCE_SSL_PORT:g" $TCE_APACHE2_PREFIX/conf/httpd.conf.template > $TCE_APACHE2_PREFIX/conf/httpd.conf.tmp
cp "$TCE_APACHE2_PREFIX/conf/httpd.conf.tmp" "$TCE_APACHE2_PREFIX/conf/httpd.conf.template" -f
sed "s:#TCE_USER#:$TCE_USER:g" $TCE_APACHE2_PREFIX/conf/httpd.conf.template > $TCE_APACHE2_PREFIX/conf/httpd.conf.tmp
cp "$TCE_APACHE2_PREFIX/conf/httpd.conf.tmp" "$TCE_APACHE2_PREFIX/conf/httpd.conf.template" -f
sed "s:#TCE_GROUP#:$TCE_GROUP:g" $TCE_APACHE2_PREFIX/conf/httpd.conf.template > $TCE_APACHE2_PREFIX/conf/httpd.conf.tmp
cp "$TCE_APACHE2_PREFIX/conf/httpd.conf.tmp" "$TCE_APACHE2_PREFIX/conf/httpd.conf.template" -f
sed "s:#TCE_APACHE2_PREFIX#:$TCE_APACHE2_PREFIX:g" $TCE_APACHE2_PREFIX/conf/httpd.conf.template > $TCE_APACHE2_PREFIX/conf/httpd.conf.tmp
# Final copy
cp "$TCE_APACHE2_PREFIX/conf/httpd.conf.tmp" "$TCE_APACHE2_PREFIX/conf/httpd.conf" -f
echo "Done!"

echo "Starting Apache2..."
if $TCE_APACHE2_PREFIX/bin/apachectl startssl;
then
	echo "Done!"
else
	echo "Could not start Apache2. Please, check the logs in $TCE_APACHE2_PREFIX/logs for the reason."
	echo "After solving the problem, you can try to start the server again by running $TCE_APACHE2_PREFIX/bin/apachectl startssl"
	echo "Afterwards, visit http://$TCE_HOSTNAME:$TCE_PORT/install.php?KEY=$TCE_KEY or https://$TCE_HOSTNAME:$TCE_SSL_PORT/install.php?KEY=$TCE_KEY to configure the Tight Control Environment."
	echo
	echo "Cleaning up..."
	cd /
	rm "$TCE_TEMP" -R
	echo "TCE Installed! (But errors occured!)"
	exit 0
fi

echo "Cleaning up..."
cd /
rm "$TCE_TEMP" -R > /dev/null 2>&1

echo "TCE Installed! Please, visit http://$TCE_HOSTNAME:$TCE_PORT/install.php?KEY=$TCE_KEY or https://$TCE_HOSTNAME:$TCE_SSL_PORT/install.php?KEY=$TCE_KEY to configure the Tight Control Environment!"
exit 0